package com.hoe.tsb.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hoe.tsb.TbsException;
import com.hoe.tsb.web.bean.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * Web容器配置
 * </p>
 *
 * @author hoe
 * @version 1.0
 * @date 2022/11/24 14:19
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class Config {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        return objectMapper;
    }

    @ExceptionHandler(value = Exception.class)
    public R<?> allExceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
        log.error("全局异常", exception);
        return R.fail("服务器运行异常");
    }

    @ExceptionHandler(value = TbsException.class)
    public R<?> validationExceptionHandler2(HttpServletRequest request, TbsException validException) throws Exception {
        log.error("业务异常", validException);
        return R.fail(validException.getMessage());
    }

}
